import os

def create_fastapi_project():
    # 项目基本信息
    project_name = "fastapi_mysql_project"
    
    # 创建项目目录
    os.makedirs(project_name, exist_ok=True)
    
    # 定义项目结构
    directories = [
        f"{project_name}/app",
        f"{project_name}/app/routers",
        f"{project_name}/app/models",
        f"{project_name}/app/database",
        f"{project_name}/app/core"
    ]
    
    # 创建所有目录
    for directory in directories:
        os.makedirs(directory, exist_ok=True)
        # 在每个目录中创建 __init__.py 文件
        init_file = os.path.join(directory, "__init__.py")
        with open(init_file, "w", encoding="utf-8") as f:
            f.write("# Package initialization\n")
    
    # 定义文件内容 - 修复编码和导入问题
    files = {
        f"{project_name}/main.py": """from fastapi import FastAPI
from app.routers import blog_router
from app.core.config import settings

app = FastAPI(title=settings.PROJECT_NAME)

app.include_router(blog_router.router)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
""",
        
        f"{project_name}/app/core/config.py": """import os
from pydantic_settings import BaseSettings  # 修复导入

class Settings(BaseSettings):
    PROJECT_NAME: str = "FastAPI MySQL 博客系统"
    DB_HOST: str
    DB_PORT: int
    DB_USER: str
    DB_PASS: str
    DB_NAME: str
    
    class Config:
        case_sensitive = True
        env_file = ".env"

settings = Settings()
""",
        
        f"{project_name}/app/database/database.py": """from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.core.config import settings

# 构建数据库连接URL
SQLALCHEMY_DATABASE_URL = f"mysql+pymysql://{settings.DB_USER}:{settings.DB_PASS}@{settings.DB_HOST}:{settings.DB_PORT}/{settings.DB_NAME}"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL,
    pool_pre_ping=True,
    pool_recycle=3600
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

# 数据库会话依赖
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
""",
        
        f"{project_name}/app/models/blog.py": """from sqlalchemy import Column, Integer, String, Text
from app.database.database import Base

class Blog(Base):
    __tablename__ = 'cms_blog'
    
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String(200))
    content = Column(Text)
    # 添加其他实际存在的字段...
    
    # 注意：确保这些字段与您的数据库表结构匹配
    # 如果表中有更多字段，请在此添加
""",
        
        f"{project_name}/app/routers/blog_router.py": """from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.models.blog import Blog
from app.database.database import get_db

router = APIRouter()

@router.get("/blogs")
async def get_blogs(db: Session = Depends(get_db)):
    try:
        blogs = db.query(Blog).limit(10).all()
        return {"data": blogs}
    except Exception as e:
        import traceback
        traceback.print_exc()  # 打印详细错误信息
        raise HTTPException(
            status_code=500, 
            detail=f"数据库错误: {str(e)}"
        )
""",
        
        f"{project_name}/requirements.txt": """fastapi
uvicorn
sqlalchemy
pymysql
python-dotenv
pydantic-settings
pydantic
""",
        
        f"{project_name}/.env": """# 数据库配置
DB_HOST=127.0.0.1
DB_PORT=3306
DB_USER=root
DB_PASS=root
DB_NAME=blog
""",
        
        f"{project_name}/README.md": """# FastAPI MySQL 项目

## 安装依赖
pip install -r requirements.txt


## 配置环境变量
编辑 .env 文件填写实际数据库连接信息

## 运行项目
python main.py


## 访问API
http://localhost:8000/blogs

## 项目结构说明
- `app/core/config.py`: 配置管理，从.env读取环境变量
- `app/database/database.py`: 数据库连接和会话管理
- `app/models/`: 数据库模型定义
- `app/routers/`: API路由定义
- `main.py`: 应用入口点
""",
        
        # 添加 .gitignore 文件避免提交敏感信息
        f"{project_name}/.gitignore": """# Python
__pycache__/
*.pyc
*.pyo
*.pyd

# Environment variables
.env

# Virtual environment
venv/
env/

# Logs
*.log

# IDE
.vscode/
.idea/
"""
    }

    # 创建所有文件（使用UTF-8编码）
    for file_path, content in files.items():
        # 确保目录存在
        dir_path = os.path.dirname(file_path)
        if not os.path.exists(dir_path):
            os.makedirs(dir_path, exist_ok=True)
        
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(content)
    
    print(f"✅ 项目 '{project_name}' 创建成功！")
    print("请按照以下步骤操作：")
    print(f"1. 进入项目目录: cd {project_name}")
    print("2. 安装依赖: pip install -r requirements.txt")
    print("3. 检查 .env 文件中的数据库配置是否正确")
    print("4. 运行项目: python main.py")
    print("5. 访问 http://localhost:8000/blogs 测试API")
    print("注意：如果遇到中文乱码问题，请确保终端支持UTF-8编码")

if __name__ == "__main__":
    create_fastapi_project()